package com.gdut.ui;

import com.gdut.domain.User;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.util.ArrayList;

public class LoginJFrame extends JFrame implements MouseListener {
    static ArrayList<User> users = new ArrayList<>();

    static {
        users.add(new User("123", "123"));
        users.add(new User("aaa", "aaa"));
    }

    public static final String FOlDER_NAME = "uploads";

    JLabel usernameLabel = new JLabel("用户名:");
    JTextField usernameField = new JTextField();
    JLabel passLabel = new JLabel("密码:");
    JPasswordField passwordField = new JPasswordField();
    JLabel tips = new JLabel("账号密码都为123或都为aaa");

    JButton loginButton = new JButton("登录");

    public LoginJFrame() {
        initial();
        this.setVisible(true);
    }

    public void initial() {
        File folder = new File(FOlDER_NAME);
        if (!folder.exists()) {
            if (!folder.mkdirs()) {
                JOptionPane.showMessageDialog(this, "初始化失败");
            }
        }
        this.setSize(450, 200);
        this.setLayout(new GridLayout(3, 2));
        this.setTitle("文件管理系统");
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        this.add(usernameLabel);
        this.add(usernameField);
        this.add(passLabel);
        this.add(passwordField);
        this.add(tips);
        this.add(loginButton);
        loginButton.addMouseListener(this);
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        if (e.getSource() == loginButton) {
            login();
        }
    }

    public boolean existUser(User inputUser) {
        for (User rightUser : users) {
            if (inputUser.equals(rightUser)) {
                return true;
            }
        }
        return false;
    }

    public void login(){
        String username = usernameField.getText();
        String password = new String(passwordField.getPassword());
        User inputUser = new User(username, password);
        if (existUser(inputUser)) {
            JOptionPane.showMessageDialog(this, "登录成功");
            this.dispose();
            new ManageJFrame();
        } else {
            JOptionPane.showMessageDialog(this, "用户名或密码错误");
        }
    }

    @Override
    public void mousePressed(MouseEvent e) {

    }

    @Override
    public void mouseReleased(MouseEvent e) {

    }

    @Override
    public void mouseEntered(MouseEvent e) {

    }

    @Override
    public void mouseExited(MouseEvent e) {

    }
}
